﻿using MediatR;
using System.ComponentModel.Design;
using T.Vehicleservice.Domain.Dtos;
using T.Vehicleservice.Domain.T.Vehicleservice.Model;
using T.Vehicleservice.Read.API.Application.Command.MaintenanceRecordCommand;
using T.Vehicleservice.Repository.Interface;

namespace T.Vehicleservice.Read.API.Application.CommandHandlers.MaintenanceRecordHandlerCommand
{
    public class MainShowHandlerCommand : IRequestHandler<MainShowCommand, PageDto<MaintenanceRecord>>
    {
        IMainIRepository mainIRepository;

        public MainShowHandlerCommand(IMainIRepository mainIRepository)
        {
            this.mainIRepository = mainIRepository;
        }

        public async Task<PageDto<MaintenanceRecord>> Handle(MainShowCommand request, CancellationToken cancellationToken)
        {
            var res =await mainIRepository.GetAsync(o => o.IsDeleted == false);
          if (!string.IsNullOrEmpty(request.MaintenanceManager))
            {
                res = res.Where(o => o.MaintenanceManager.Contains(request.MaintenanceManager)).ToList();
            }
            if (!string.IsNullOrEmpty(request.LicensePlateNumber))
            {
                res = res.Where(o => o.LicensePlateNumber.Contains(request.LicensePlateNumber)).ToList();
            }
            if (request.RepairDate != null)
            {
                res = res.Where(o => o.RepairDate==request.RepairDate).ToList();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                res = res.Where(o => o.CompanyID == request.CompanyID).ToList();
            }
            if (request.Pagesize==null)
            {
                request.Pagesize=res.Count();
            }
            PageDto<MaintenanceRecord>pageDto= new PageDto<MaintenanceRecord>();
            pageDto.TotalCount = res.Count();
           
            pageDto.PageCount = (int)Math.Ceiling(pageDto.TotalCount * 1.0 / (int)request.Pagesize);
            pageDto.list=res.OrderByDescending(o=>o.MaintenanceId).Skip((int)(request.Pageindex-1)*(int)request.Pagesize).Take((int)request.Pagesize).ToList();
            return pageDto;

        }
    }

   
    
}
